const { app, BrowserWindow } = require("electron");
const path = require("node:path");
const fs = require("fs");
const { exec } = require("child_process");
const { session } = require("electron");

/**
 * @type {BrowserWindow}
 */
let loadingWindow;
/**
 * @type {BrowserWindow}
 */
let mainWindow;

// 默认config.json内容
let jsonFile = `
{
  "liveroomURL": "https://live.bilibili.com/139",
  "config": [
    ["一个特定的目标", "Warning! The designated target has been detected."],
    ["帅Pi", "帅皮哎牌子"],
    ["狸头人", "狸头人牌子"],
    ["陆夫人", "陆夫人牌子"],
    ["大母鹅", "大母鹅牌子"],
    ["为主播点赞了", "有人点赞主播"]
  ]
}
`;
let jsonData = JSON.parse(jsonFile);
if (!fs.existsSync("config.json")) {
  console.log("不存在config.json文件, 将创建该文件");
  // 创建config.json文件并写入内容
  fs.writeFileSync("config.json", jsonFile);
  console.log("config.json文件已创建并写入内容");
} else {
  console.log("存在config.json文件");
}
// 读取config.json
try {
  const file = fs.readFileSync("config.json", "utf8");
  jsonFile = file;
  jsonData = JSON.parse(file);
} catch (err) {
  if (err) {
    console.error(err);
  } else {
    console.error("解析 JSON 失败", err);
  }
}
// 将字符串转换为Buffer
const jsonFilebuffer = Buffer.from(jsonFile, "utf8");
// 将Buffer转换为Base64编码
const jsonFileBase64 = jsonFilebuffer.toString("base64");

/**
 * @type {string}
 */
let liveroomURL = jsonData.liveroomURL;

if (!liveroomURL.includes("live") || !liveroomURL.includes("bilibili")) {
  exec('msg %username% "仅支持bilibili直播间链接"');
  setTimeout(() => {
    process.exit(0);
  }, 10);
}

// 加载loading页面窗口
const showLoading = () => {
  loadingWindow = new BrowserWindow({
    width: 74,
    height: 74,
    frame: false,
    transparent: true,
  });
  loadingWindow.loadFile("loading.html");
  loadingWindow.show();
};

const createWindow = () => {
  mainWindow = new BrowserWindow({
    width: 180,
    height: 100,
    show: false,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });
  mainWindow.once("ready-to-show", () => {
    // 模拟启动准备时间
    setTimeout(() => {
      loadingWindow.hide();
      loadingWindow.close();
      mainWindow.show();
    }, 1500);
  });
  // 先静音，防止直播声音吓一跳
  mainWindow.webContents.setAudioMuted(true);
  // 加载b站直播间
  mainWindow.loadURL(liveroomURL);
  // 隐藏菜单栏
  mainWindow.setMenu(null);
  // 打开控制台
  if (!app.isPackaged) {
    mainWindow.webContents.openDevTools(true);
  }
  // 将读取的json文件以base64的形式装载到元素中, 让 preload.js 可以正常读取
  mainWindow.webContents.on("did-finish-load", () => {
    // 延迟取消静音，防止直播声音吓一跳
    setTimeout(() => {
      mainWindow.webContents.setAudioMuted(false);
    }, 1000);
    mainWindow.webContents.executeJavaScript(
      `
      var jsonFileElement = document.createElement("p");
      jsonFileElement.textContent = \`` +
        jsonFileBase64 +
        `\`;
      jsonFileElement.id = "jsonFileElement";
      document.body.appendChild(jsonFileElement);
      jsonFileElement.style.display = "none";
    `
    );
  });
};

app.whenReady().then(() => {
  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        "Content-Security-Policy": [
          "style-src 'self' 'unsafe-inline' https://s1.hdslb.com https://static.geetest.com https://dn-staticdown.qbox.me;",
          "img-src 'self' data: https://www.bilibili.com https://static.hdslb.com https://i0.hdslb.com https://i1.hdslb.com https://i2.hdslb.com https://s1.hdslb.com https://hm.baidu.com;",
        ],
      },
    });
  });

  showLoading();
  createWindow();

  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});
